import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import LocalCache from '@/utils/cache'
import { firstMenu } from '@/utils/MenusToRoutes'
// RouteRecordRaw是routes的类型
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    name: 'login',
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "login" */ 'views/login/Login.vue')
  },
  {
    name: 'main',
    path: '/main',
    component: () =>
      import(/* webpackChunkName: "main" */ 'views/main/Main.vue')
    // 路由children的加载方式
    // children: [
    //   // 1.写死所有路由
    //   // 2.不同的角色注册不同的路由
    //   // 3.动态的加载,通过返回的url,来加载对应的路由
    //   // 在导航守卫中做路由注册
    //   // 在vuex中拿到userMenus后面做路由注册
    // ]
  },
  {
    name: 'notfound',
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/notfound/notfound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 导航守卫
router.beforeEach((to) => {
  if (to.path !== '/login') {
    const token = LocalCache.getCache('token')
    if (!token) {
      return '/login'
    }
  }

  if (to.path === '/main') {
    return firstMenu.url
  }
})

export default router
